import os
import tkinter as tk
import threading
from tkinter import filedialog, messagebox
from mp3 import process_and_merge
from srt import merge_srt_files, get_srt_files
from rename import random_rename_files, sequential_rename_files, random_then_sort_rename_files
from config import CONFIG
from updater import Updater
from datetime import datetime

class MediaToolApp:
    def __init__(self, root):
        self.root = root
        self.root.title(f"{CONFIG['TITLE']} {CONFIG['VERSION']}")
        self.root.geometry("450x700")
        self.root.resizable(False, False)
        self.start_cut_var = tk.StringVar(value="50")
        self.end_cut_var = tk.StringVar(value="100")
        self.setup_ui()

    def setup_ui(self):
        # 字体设置
        title_font = ('Tahoma', 10, 'bold')
        normal_font = ('Tahoma', 10)
        
        # 主框架
        main_frame = tk.Frame(self.root, padx=10, pady=10)
        main_frame.pack(fill=tk.BOTH, expand=True)
        
        # 音频合并部分
        self.create_audio_section(main_frame, title_font, normal_font)
        
        # 字幕合并部分
        self.create_srt_section(main_frame, title_font, normal_font)
        
        # 批量改名部分
        self.create_rename_section(main_frame, title_font, normal_font)
        
        # 状态显示标签
        self.status_label = tk.Label(main_frame, text="等待操作...", fg="gray", font=normal_font)
        self.status_label.pack(pady=20)

        # 添加更新控件（位于最底部）
        self.update_label = tk.Label(self.root, text="检查更新", font=normal_font, anchor="se", cursor="hand2")
        self.update_label.pack(side=tk.BOTTOM, padx=10, pady=10, anchor="se")
        self.update_auto()

    def create_audio_section(self, parent, title_font, normal_font):
        frame = tk.LabelFrame(parent, text="音频合并", font=title_font, height=200) 
        frame.pack(fill="x", pady=10)
        frame.pack_propagate(False)
        
        self.audio_folder_var = tk.StringVar()
        self.audio_output_var = tk.StringVar()
        
        # 选择音频目录行
        self.create_directory_row(frame, "选择音频目录:", self.audio_folder_var, 
                                 self.select_audio_folder, normal_font)
        
        # 选择输出目录行
        self.create_directory_row(frame, "选择输出目录:", self.audio_output_var, 
                                 self.select_audio_output, normal_font)
        
        # 添加裁剪时间设置行
        cut_frame = tk.Frame(frame)
        cut_frame.pack(fill="x", padx=5, pady=5)
        cut_frame.columnconfigure(1, weight=1)
        cut_frame.columnconfigure(3, weight=1)
        
        tk.Label(cut_frame, text="开头裁剪(毫秒):", font=normal_font).grid(row=0, column=0, padx=5, sticky="w")
        tk.Entry(cut_frame, textvariable=self.start_cut_var, font=normal_font, width=10).grid(row=0, column=1, padx=5, sticky="w")
        
        tk.Label(cut_frame, text="结尾裁剪(毫秒):", font=normal_font).grid(row=0, column=2, padx=5, sticky="w")
        tk.Entry(cut_frame, textvariable=self.end_cut_var, font=normal_font, width=10).grid(row=0, column=3, padx=5, sticky="w")
        
        # 合并音频按钮
        btn = tk.Button(frame, text="合并音频", command=self.merge_audio, 
                       width=20, height=2, font=normal_font)
        btn.pack(pady=10)

    def create_srt_section(self, parent, title_font, normal_font):
        frame = tk.LabelFrame(parent, text="字幕合并", font=title_font, height=170)
        frame.pack(fill="x", pady=10)
        frame.pack_propagate(False)
        
        self.srt_folder_var = tk.StringVar()
        self.srt_output_var = tk.StringVar()
        
        # 选择字幕目录行
        self.create_directory_row(frame, "选择字幕目录:", self.srt_folder_var, 
                                 self.select_srt_folder, normal_font)
        
        # 选择输出目录行
        self.create_directory_row(frame, "选择输出目录:", self.srt_output_var, 
                                 self.select_srt_output, normal_font)
        
        # 合并字幕按钮
        btn = tk.Button(frame, text="合并SRT", command=self.merge_srt, 
                       width=20, height=2, font=normal_font)
        btn.pack(pady=10)

    def create_rename_section(self, parent, title_font, normal_font):
        frame = tk.LabelFrame(parent, text="批量改名", font=title_font, height=120)
        frame.pack(fill="x", pady=10)
        frame.pack_propagate(False)
        
        self.rename_folder_var = tk.StringVar()
        
        # 选择改名目录行
        self.create_directory_row(frame, "选择改名目录:", self.rename_folder_var, 
                                 self.select_rename_folder, normal_font)
        
        # 批量改名按钮
        btn_frame = tk.Frame(frame)
        btn_frame.pack(pady=10)
        
        btn1 = tk.Button(btn_frame, text="随机生成文件名", command=self.random_rename, font=normal_font)
        btn1.pack(side=tk.LEFT, padx=10)
        
        btn2 = tk.Button(btn_frame, text="随机后重排序", command=self.random_then_sort_rename, font=normal_font)
        btn2.pack(side=tk.LEFT, padx=10)

        btn3 = tk.Button(btn_frame, text="按顺序重命名", command=self.sequential_rename, font=normal_font)
        btn3.pack(side=tk.LEFT, padx=10)

    def create_directory_row(self, parent, label_text, var, command, font):
        frame = tk.Frame(parent)
        frame.pack(fill="x", padx=5, pady=10)
        frame.columnconfigure(1, weight=1)
        
        tk.Label(frame, text=label_text, font=font).grid(row=0, column=0, padx=5, sticky="w")
        tk.Entry(frame, textvariable=var, font=font).grid(row=0, column=1, padx=5, sticky="ew")
        tk.Button(frame, text="选择目录", command=command, font=font).grid(row=0, column=2, padx=5)

    # 目录选择方法
    def select_audio_folder(self):
        folder = filedialog.askdirectory()
        if folder:
            self.audio_folder_var.set(folder)

    def select_audio_output(self):
        folder = filedialog.askdirectory()
        if folder:
            self.audio_output_var.set(folder)

    def select_srt_folder(self):
        folder = filedialog.askdirectory()
        if folder:
            self.srt_folder_var.set(folder)

    def select_srt_output(self):
        folder = filedialog.askdirectory()
        if folder:
            self.srt_output_var.set(folder)

    def select_rename_folder(self):
        folder = filedialog.askdirectory()
        if folder:
            self.rename_folder_var.set(folder)

    def merge_audio_worker(self):
        audio_folder = self.audio_folder_var.get()
        audio_output = self.audio_output_var.get()
        
        # 验证裁剪时间输入
        try:
            start_cut = int(self.start_cut_var.get())
            end_cut = int(self.end_cut_var.get())
            if start_cut < 0 or end_cut < 0:
                raise ValueError("时间不能为负数")
        except ValueError as e:
            messagebox.showerror("输入错误", f"裁剪时间设置错误: {str(e)}")
            return
        
        if not self.validate_directory(audio_folder, "请选择音频目录"):
            return
        if not self.validate_directory(audio_output, "请选择输出目录"):
            return
        
        timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
        output_file = f"{audio_output}/merged_audio_{timestamp}.mp3"
        
        def progress_callback(file):
            self.update_status(f"正在处理文件: {file}")
            
        try:
            # 传递裁剪时间参数给处理函数
            success, message = process_and_merge(
                audio_folder, 
                output_file, 
                progress_callback,
                start_cut=start_cut,
                end_cut=end_cut
            )
            self.show_result(success, message)
        except Exception as e:
            self.show_result(False, f"发生错误: {str(e)}")

    def merge_audio(self):
        threading.Thread(target=self.merge_audio_worker).start()

    def merge_srt(self):
        srt_folder = self.srt_folder_var.get()
        srt_output = self.srt_output_var.get()
        
        if not self.validate_directory(srt_folder, "请选择字幕目录"):
            return
        if not self.validate_directory(srt_output, "请选择输出目录"):
            return
        
        srt_files = get_srt_files(srt_folder)
        if not srt_files:
            messagebox.showerror("错误", "所选目录中未找到SRT文件")
            return
            
        timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
        output_path = f"{srt_output}/merged_subtitles_{timestamp}.srt"
        
        try:
            success, message = merge_srt_files(srt_files, output_path)
            self.show_result(success, message)
        except Exception as e:
            self.show_result(False, f"发生错误: {str(e)}")

    def random_rename(self):
        self.perform_rename_operation(random_rename_files, "随机生成文件名")

    def sequential_rename(self):
        self.perform_rename_operation(sequential_rename_files, "按顺序重命名")

    def random_then_sort_rename(self):
        self.perform_rename_operation(random_then_sort_rename_files, "随机后重排序")

    def perform_rename_operation(self, operation, operation_name):
        folder = self.rename_folder_var.get()
        if not self.validate_directory(folder, "请选择目录"):
            return
            
        try:
            success, message = operation(folder)
            self.show_result(success, f"{operation_name}: {message}")
        except Exception as e:
            self.show_result(False, f"{operation_name}时发生错误: {str(e)}")

    # 辅助方法
    def validate_directory(self, directory, error_message):
        if not directory:
            messagebox.showerror("错误", error_message)
            return False
        if not os.path.isdir(directory):
            messagebox.showerror("错误", f"目录不存在: {directory}")
            return False
        return True
    
    # 显示结果
    def show_result(self, success, message):
        self.update_status(message)
        """
        if success:
            messagebox.showinfo("完成", message)
        else:
            messagebox.showerror("错误", message)
        """
    
    # 处理方法
    def update_status(self, message):
        self.status_label.config(text=message)
        self.root.update_idletasks()

    # 自动更新
    def update_auto(self):
        self.updater = Updater(root, self.update_label_status)
        self.updater.check_update(manual_check=False)

    # 手动更新
    def update_manual(self):
        self.updater = Updater(root, self.update_label_status)
        self.update_label.bind("<Button-1>", lambda e: self.updater.check_update(manual_check=True))

    # 更新状态回调函数
    def update_label_status(self, msg):
        if self.updater.new_east and self.updater.link_name and self.updater.link_url:
            link_url = self.updater.link_url
            self.update_label.config(text=self.updater.link_name, foreground="blue")
        else:
            link_url = self.updater.download_url
            self.update_label.config(text=msg, foreground="red")
        # 解绑原有事件，绑定新事件（打开链接）
        self.update_label.unbind("<Button-1>")
        self.update_label.bind("<Button-1>", lambda event: self.updater.open_link(event, link_url))

if __name__ == "__main__":
    root = tk.Tk()
    app = MediaToolApp(root)
    root.mainloop()